import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { Property, PropertyStats, SearchParams, ApiResponse, PaginatedResponse } from '@/types/property'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8082/api', // Spring Boot后端地址
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    console.error('API请求错误:', error)
    if (error.response?.status === 401) {
      // token过期，跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('isLoggedIn')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('isLoggedIn')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 房产管理API接口
export const propertyApi = {
  
  /**
   * 搜索分页查询房产列表
   * @param params - 查询参数
   * @returns 
   */
  searchProperties(params: SearchParams): Promise<PaginatedResponse<Property>> {
    return api.get('/properties/search', { params })
  },

  /**
   * 获取房产详情
   * @param id - 房产ID
   * @returns 
   */
  getPropertyDetail(id: string): Promise<ApiResponse<Property>> {
    return api.get(`/properties/${id}`)
  },

  /**
   * 新增房产
   * @param propertyData - 房产数据
   * @returns 
   */
  createProperty(propertyData: Omit<Property, 'id'>): Promise<ApiResponse<Property>> {
    return api.post('/properties', propertyData)
  },

  /**
   * 更新房产信息
   * @param id - 房产ID
   * @param propertyData - 房产数据
   * @returns 
   */
  updateProperty(id: string, propertyData: Partial<Property>): Promise<ApiResponse<Property>> {
    return api.put(`/properties/${id}`, propertyData)
  },

  /**
   * 删除房产
   * @param id - 房产ID
   * @returns 
   */
  deleteProperty(id: string): Promise<ApiResponse<void>> {
    return api.delete(`/properties/${id}`)
  },

  /**
   * 获取房产统计信息
   * @returns 
   */
  getPropertyStats(): Promise<ApiResponse<PropertyStats>> {
    return api.get('/properties/stats')
  },

  /**
   * 获取所有楼栋列表
   * @returns 
   */
  getBuildings(): Promise<ApiResponse<string[]>> {
    return api.get('/properties/buildings')
  }
}

// 导出默认实例
export default api